package com.example.demo.excel;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.List;

import org.apache.commons.lang.StringUtils;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.exception.ExcelCommonException;
import com.alibaba.excel.read.builder.ExcelReaderBuilder;
import com.alibaba.excel.read.listener.ReadListener;

public class ExcelUtil {
    public static <T> List<T> read(File file, int sheetNo, int headNum, Class<T> clazz, PointsListener<T> listener) {
        ExcelReaderBuilder excelReaderBuilder = getExcelReaderBuilder(file, clazz, listener);
        if (null == excelReaderBuilder) {
            return null;
        } else {
            excelReaderBuilder.sheet(sheetNo).headRowNumber(headNum).doRead();
            return listener.getList();
        }
    }

    private static <T> ExcelReaderBuilder getExcelReaderBuilder(File file, Class<T> clazz, ReadListener<T> listener) {

        String name = file.getName();
        if (!StringUtils.endsWithIgnoreCase(name, "xls") && !StringUtils.endsWithIgnoreCase(name, "xlsx")) {
            throw new ExcelCommonException("文件格式不对");
        } else {
            BufferedInputStream bis = null;
            try {
                bis = new BufferedInputStream(new FileInputStream(file));
                return EasyExcel.read(bis, clazz, listener);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
                return null;
            }
        }
    }
}
